/** Description of BrandEdit.java 
 *
 * @author panther
 * Jayant Pratim Saikia
 * jay.saikia@gmail.com
 *
 */
package com.panther.awp.android.smoker.activities;


import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

import com.panther.awp.android.smoker.R;
import com.panther.awp.android.smoker.cache.Cache;
import com.panther.awp.android.smoker.database.AbstractDbAdapter;
import com.panther.awp.android.smoker.database.MyDBWrapper;

public class BrandEdit extends Activity {
	
	private long mId;
	private MyDBWrapper mDBWrapper;
	private Button saveButton;
	private EditText brandName;
	private EditText brandPrice;
	private Button cancelButton;
	private ImageButton brandImageButton;
	private Boolean imageSelectedOrChanged = false;
	
	private static final int SELECT_PHOTO = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.brandedit);
		mDBWrapper = MyDBWrapper.getInstance(getApplicationContext());
		brandName = (EditText) findViewById(R.id.brand_edit_name);
		brandPrice = (EditText) findViewById(R.id.brandprice_edit_name);
		brandImageButton = (ImageButton) findViewById(R.id.brandImageButton);
		Bundle extras = getIntent().getExtras();
		if(extras == null) {
			brandImageButton.setImageResource(R.drawable.icon);
			saveButton = (Button) findViewById(R.id.saveBrand);
			saveButton.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					if(!brandName.getText().toString().equalsIgnoreCase("") && !brandPrice.getText().toString().equalsIgnoreCase("")) {
						if(imageSelectedOrChanged) {
							String bitmapUri = Cache.getRandomUriForBitmap();
							Bitmap brandIcon = ((BitmapDrawable)brandImageButton.getDrawable()).getBitmap();
							Cache.saveCacheFile(bitmapUri, brandIcon);
							ContentValues values = new ContentValues();
							values.put(AbstractDbAdapter.BT_BRAND, brandName.getText().toString());
							values.put(AbstractDbAdapter.BT_BRAND_PRICE, Double.parseDouble(brandPrice.getText().toString()));
							values.put(AbstractDbAdapter.BT_IMAGE_URI, bitmapUri);
							values.put(AbstractDbAdapter.BT_NO_OF_CIGGS, 0);
							mDBWrapper.getmBTDbHelper().create(values);
						} else {
							ContentValues values = new ContentValues();
							values.put(AbstractDbAdapter.BT_BRAND, brandName.getText().toString());
							values.put(AbstractDbAdapter.BT_BRAND_PRICE, Double.parseDouble(brandPrice.getText().toString()));
							values.put(AbstractDbAdapter.BT_IMAGE_URI, "NO_IMAGE");
							values.put(AbstractDbAdapter.BT_NO_OF_CIGGS, 0);
							mDBWrapper.getmBTDbHelper().create(values);
						}
						finish();
						overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
					} else {
						Toast toast = Toast.makeText(getApplicationContext(), R.string.brand_already_created, Toast.LENGTH_LONG);
						toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 30);
						toast.show();
					}
				}
			});
			
		} else {
			mId = extras.getLong(AbstractDbAdapter.BT_PK_ID);
			Cursor cursor = mDBWrapper.getmBTDbHelper().fetch(mId);
			cursor.moveToFirst();
			while(!cursor.isAfterLast()) {
				brandName.setText(cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND)));
				brandPrice.setText(cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE)));
				String brandUri = cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_IMAGE_URI));
				if(brandUri.equals("NO_IMAGE")) {
					brandImageButton.setImageResource(R.drawable.icon);
				} else {
					brandImageButton.setImageBitmap(Cache.getCacheFile(brandUri));
				}
				cursor.moveToNext();
			}
			brandPrice.setClickable(false);
			brandPrice.setFocusable(false);
			saveButton = (Button) findViewById(R.id.saveBrand);
			saveButton.setText("Edit Brand");
			saveButton.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					if(!brandName.getText().toString().equalsIgnoreCase("")) {
						ContentValues values = new ContentValues();
						values.put(AbstractDbAdapter.BT_BRAND, brandName.getText().toString());
						if(imageSelectedOrChanged) {
							String bitmapUri = Cache.getRandomUriForBitmap();
							Bitmap brandIcon = ((BitmapDrawable)brandImageButton.getDrawable()).getBitmap();
							Cache.saveCacheFile(bitmapUri, brandIcon);
							values.put(AbstractDbAdapter.BT_IMAGE_URI, bitmapUri);
						}
						mDBWrapper.getmBTDbHelper().update(mId, values);
						finish();
						overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
					}
				}
			});
			
			//brandImageButton
		}
		cancelButton = (Button) findViewById(R.id.cancelSave);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				finish();
				overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
			}
		});
		
		brandImageButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
				photoPickerIntent.setType("image/*");
				startActivityForResult(photoPickerIntent, SELECT_PHOTO);
				
			}
		});
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

	    switch(requestCode) { 
	    case SELECT_PHOTO:
	        if(resultCode == RESULT_OK){
	        	imageSelectedOrChanged = true;
	            Uri selectedImage = imageReturnedIntent.getData();
	            try {
					Bitmap yourSelectedImage = decodeUri(selectedImage);
					brandImageButton.setImageBitmap(yourSelectedImage);
					brandImageButton.setScaleType(ScaleType.FIT_XY);
				} catch (FileNotFoundException e) {
					brandImageButton.setImageResource(R.drawable.icon);
				}
	        }
	    }

	}

	private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 140;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE
            || height_tmp / 2 < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);

    }


}
